﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MySql.Data.MySqlClient;
using LdExpress;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    public string ContainerPage = "./Carrs.aspx";
    public string strCondition = "";
    public int NumOfItemsPerPage = 20;
    public string strPager = "";
    public string strIDs = "";
    public string strError = "";
    public string strMess = "";
    public int nPermissions = 0;
    public int nPage = 1;
    public string strPageID = "page_number";
    public string strLetter = "letter";
    public string strAlphaBet = "";
    public string strChar = "";
    public string strExcluded = "CarrsID";
    public string strPartQuery = "";
    protected void Page_Load(object sender, EventArgs e)
    {

        int nPage = 1;
        try
        {

            if (Request.QueryString[strPageID] != null)
                nPage = int.Parse(Request.QueryString[strPageID]);
        }
        catch
        {
            nPage = 1;
        }
        if (nPage <= 0) nPage = 1;


        try
        {

            if (Request.QueryString[strLetter] != null)
            {
                strChar = Request.QueryString[strLetter].ToString();
                strCondition = " AND tbl_carrs.Name like '" + strChar + "%'";
            }
        }
        catch
        {
            strChar = "";
        }

        if ((Session["logined_id"] != null) && (int.Parse(Session["logined_id"].ToString()) > 0))
        {
            if (Session["Carrs"] != "") nPermissions = int.Parse(Session["Carrs"].ToString());
        }
        else
            Response.Redirect("Login.aspx");

        if (!Page.IsPostBack)
        {
            CommonFunctions.GetAllQueryString(Request, "", "action;CarrsID", out strPartQuery);
            if (Request.QueryString["action"] == "delete" && nPermissions > 7)
            {
                Carrs obj = new Carrs();
                obj.ID = long.Parse(Request.QueryString["CarrsID"]);
                obj.Load(GV.cn, GV.trans);
                string strFileName = Server.MapPath("./") + "\\Assets\\Js\\Carrs.js";

                StreamReader sr = new StreamReader(strFileName, System.Text.Encoding.UTF8);
                string strName = sr.ReadToEnd();
                sr.Close();

                string strNameRemove = "\"" + obj.Name.Trim() + "\",";
                strName = System.Text.RegularExpressions.Regex.Replace(strName, strNameRemove, "");
                strNameRemove = "\"" + obj.Name.Trim() + "\"";
                strName = System.Text.RegularExpressions.Regex.Replace(strName, strNameRemove, "");
                StreamWriter sw;
                sw = new StreamWriter(strFileName, false);
                sw.Write(strName);
                sw.Close();
                obj.Delete(GV.cn, GV.trans);
                string strDelPrice = "Delete From tbl_Prices where CarrID=" + Request.QueryString["CarrsID"].ToString();
                DBModule.ExecuteNonQuery(strDelPrice, GV.cn, GV.trans);
                Response.Redirect("Carrs.aspx" + strPartQuery);
            }
            else if (Request.QueryString["action"] == "syndata" && nPermissions > 7)
            {
                if (int.Parse(Request.QueryString["CarrsID"].ToString()) > 0)
                {
                    SynDataToCarr(Request.QueryString["CarrsID"].ToString());
                    Response.Redirect("Carrs.aspx" + strPartQuery);
                }
            }
            else
            {
                if (Request.QueryString["custID"] != null)
                {
                }
                if (Request.QueryString["carrsID"] != null)
                {
                    loadCarrs();
                }
            }
            #region Build List
            int nNumOfPages = 0;

            DataTable dtList;
            BuildList(strCondition, NumOfItemsPerPage, nPage, out nNumOfPages, out dtList, null, null);
            if (nPage > nNumOfPages) nPage = 1;

            rptData.DataSource = dtList;
            rptData.DataBind();
            #endregion
            #region Build Pager
            CommonFunctions.BuildPager(Request, nNumOfPages, nPage, strPageID, ContainerPage, out strPager);
            #endregion
            CommonFunctions.BuildAphabetSearch(Request, ContainerPage, strLetter, strChar, strExcluded, out strAlphaBet);
        }

    }
    protected void loadCarrs()
    {
        Carrs obj = new Carrs();
        obj.ID = long.Parse(Request.QueryString["carrsID"]);
        obj.Load(GV.cn, GV.trans);
        txtCarrs.Text = HttpUtility.HtmlDecode(obj.Name);
        txtRank.Text = HttpUtility.HtmlDecode(obj.Rank);
        txtServiceArea.Text = HttpUtility.HtmlDecode(obj.ServiceArea);
        txtFullName.Text = obj.FullName;
        txtInvoicingName.Text = obj.InvoicingName;
        txtAdd.Text = obj.Address;
        txtMST.Text = obj.MST;
        txtNote.Text = obj.Description;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        strError = "";
        strMess = "";
        string sqlCommand = "";
        DataSet ds = null;
        Carrs obj = new Carrs();
        obj.ID = -1;
        if (Request.QueryString["CarrsID"] != null)
        {
            obj.ID = long.Parse(Request.QueryString["CarrsID"]);
            obj.Load(GV.cn, GV.trans);
        }
        obj.Name = txtCarrs.Text.Trim();
        if (obj.Name != txtCarrs.Text.Trim())
        {
            obj.LastUpdate = DateTime.Now;
        }
        if (txtRank.Text != "")
            obj.Rank = txtRank.Text;

        string strCcatCode = CommonFunctions.UnicodeToPlain(obj.Name.Trim()).Replace(" ", "-");
        strCcatCode = System.Text.RegularExpressions.Regex.Replace(strCcatCode, @"[^\w\.-]", "");
        strCcatCode = Carrs.GetUniqueCode(obj.ID, strCcatCode, GV.cn, GV.trans).ToLower();
        obj.Code = strCcatCode;
        try
        {
            obj.Sort = int.Parse(txtSort.Text);
        }
        catch { obj.Sort = 0; }
        obj.ServiceArea = txtServiceArea.Text;
        obj.FullName = txtFullName.Text;
        obj.InvoicingName = txtInvoicingName.Text.Trim();
        obj.Address = txtAdd.Text.Trim();
        obj.MST = txtMST.Text.Trim();
        obj.Description = txtNote.Text.Trim();
        if (strError == "")
        {
            obj.Save(GV.cn, GV.trans);
            if (obj.ID == -1)
            {
                sqlCommand = "Select Max(ID) as ID from tbl_carrs";
                ds = DBModule.ExecuteQuery(sqlCommand, GV.cn, GV.trans);
                SynDataToCarr(ds.Tables[0].Rows[0]["ID"].ToString());
            }
        }
        sqlCommand = "select Name from tbl_Carrs order by Name;";
        ds = DBModule.ExecuteQuery(sqlCommand, GV.cn, GV.trans);
        string strName = "";
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            if (strName.Length > 0) strName += ",";
            strName += "\"" + dr["Name"].ToString().Trim() + "\"";
        }
        string strFileName = Server.MapPath("./") + "\\Assets\\Js\\Carrs.js";
        StreamWriter sw;

        strName = "var carrs = [" + strName + "];";
        sw = new StreamWriter(strFileName, false);
        sw.Write(strName);
        sw.Close();
        CommonFunctions.GetAllQueryString(Request, "", "action;CarrsID", out strPartQuery);
        Response.Redirect("Carrs.aspx" + strPartQuery);
    }
    private void BuildList(string strCondition, int NumOfItemsPerPage, int PageNo, out int nNumOfPages, out DataTable dtList, MySqlConnection cn, MySqlTransaction trans)
    {
        DataSet ds = null;
        dtList = new DataTable();
        dtList.Columns.Add("Sort");
        dtList.Columns.Add("Index");
        dtList.Columns.Add("Name");
        dtList.Columns.Add("Rank");
        dtList.Columns.Add("ServiceArea");
        dtList.Columns.Add("FullName");
        dtList.Columns.Add("InvoicingName");
        dtList.Columns.Add("Address");
        dtList.Columns.Add("MST");
        dtList.Columns.Add("Note");
        dtList.Columns.Add("Action");
        //Get List by SoIDs
        nNumOfPages = 0;

        if (strCondition == "") strCondition = "All";
        Carrs obj = new Carrs();


        Carrs.GetList(strCondition, "Name", NumOfItemsPerPage, PageNo, out nNumOfPages, out ds, GV.cn, GV.trans);

        string strAllQueryString = "";

        foreach (string strKey in Request.QueryString.AllKeys)
        {
            if (strKey != null)
            {
                if ((strKey.ToLower() != "action") && (strKey.ToLower() != "id"))
                    strAllQueryString = strAllQueryString + "&" + strKey + "=" + Request.QueryString[strKey].ToString();
            }
        }

        if (strAllQueryString.Length >= 1)
            strAllQueryString = strAllQueryString.Substring(1);

        if (ds != null)
        {
            int count = 0;
            if (Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "")
            {
                int pagenumber = 1;
                try
                {
                    pagenumber = int.Parse(Request.QueryString["page_number"]);
                    count = NumOfItemsPerPage * (pagenumber - 1);
                }
                catch { count = 0; }
            }
            foreach (DataRow dr in ds.Tables[0].Rows)
            {

                count++;
                string strSTT = dr["Sort"].ToString();
                string strIndex = count.ToString();
                string strCarr = dr["Name"].ToString();
                string strTitle = "";
                if (dr["LastUpdate"].ToString() != "")
                {
                    strTitle = "title=\"" + DateTime.Parse(dr["LastUpdate"].ToString()).ToString("dd - MM - yyyy") + "\"";
                    strCarr = "<span title=\"" + DateTime.Parse(dr["LastUpdate"].ToString()).ToString("dd - MM - yyyy") + "\">" + dr["Name"].ToString() + "</span>";
                }
                if (nPermissions >= 3)
                    strCarr = "<a  " + strTitle + "href=\"Carrs.aspx?CarrsID=" + dr["ID"].ToString() +
                        ((Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "") ? "&page_number=" + Request.QueryString["page_number"].ToString() : "") +
                        ((Request.QueryString["letter"] != null && Request.QueryString["letter"].ToString() != "") ? "&letter=" + Request.QueryString["letter"].ToString() : "") +
                        "\">" + dr["Name"].ToString() + "</a>";

                string strAction = "";
                string strTemp = dr["Name"].ToString();
                string strRank = dr["Rank"].ToString();
                //string strLocationName = dr["LocationName"].ToString();
                string strServiceArea = dr["ServiceArea"].ToString();
                string FullName = dr["FullName"].ToString();
                string InvoicingName = dr["InvoicingName"].ToString();
                string Address = dr["Address"].ToString();
                string MST = dr["MST"].ToString();
                string Note = dr["Description"].ToString();

                strTemp = strTemp.Replace("'", "\\'");
                if (nPermissions >= 3)
                    strAction = "<a href=\"Carrs.aspx?CarrsID=" + dr["ID"].ToString() + ((Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "") ? "&page_number=" + Request.QueryString["page_number"].ToString() : "") +
                    ((Request.QueryString["letter"] != null && Request.QueryString["letter"].ToString() != "") ? "&letter=" + Request.QueryString["letter"].ToString() : "") +
                    "\">Edit</a>";
                if (nPermissions > 7)
                {
                    strAction += " - <a href=\"javascript:doDelete('" + System.Web.HttpUtility.HtmlEncode(dr["ID"].ToString()) + "','" + System.Web.HttpUtility.HtmlEncode(strTemp) + "')\">" + "Xóa</a>";
                    strAction += " - <a href=\"javascript:doSynData('" + System.Web.HttpUtility.HtmlEncode(dr["ID"].ToString()) + "','" + System.Web.HttpUtility.HtmlEncode(strTemp) + "')\">" + "Syn Data</a>";
                }
                string[] strValues = new string[] { strSTT, strIndex, strCarr, strRank, 
                    strServiceArea,
                    FullName,
                    InvoicingName,
                    Address,
                    MST,
                    Note,
                    strAction };
                dtList.Rows.Add(strValues);
            }
        }
    }
    private void SynDataToCarr(string carrID)
    {

        Carrs obj = new Carrs();
        obj.ID = long.Parse(carrID);
        obj.Load(GV.cn, GV.trans);
        string sqlCommand = "";
        string sql = "";
        //Update CarrName
        sqlCommand = "UPDATE `tbl_prices` SET `CarrName`='" + DBModule.RefineString(obj.Name) + "' WHERE `CarrID`=" + obj.ID;
        DBModule.ExecuteNonQuery(sqlCommand, GV.cn, GV.trans);
        sqlCommand = "Select  DISTINCT PortToID,PortFromID FROM tbl_prices";
        DataSet ds = DBModule.ExecuteQuery(sqlCommand, GV.cn, GV.trans);
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                sqlCommand = "Select Id from tbl_prices where PortToID=" + dr["PortToID"].ToString() +
                   " AND PortFromID=" + dr["PortFromID"].ToString() + " AND CarrID=" + carrID;
                DataSet dsCheck = DBModule.ExecuteQuery(sqlCommand, GV.cn, GV.trans);
                if (dsCheck.Tables[0].Rows.Count == 0)
                {
                    sql += "Insert Into tbl_Prices (CarrID,CarrName,PortToID,PortFromID) values(" +
                    carrID + ",'" + obj.Name + "'," + dr["PortToID"].ToString() + "," + dr["PortFromID"].ToString() + ");";
                }
            }
            if (sql.Length > 0)
                DBModule.ExecuteNonQuery(sql, GV.cn, GV.trans);
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string strCondition = "";
        if (txtCarrsSearch.Text.ToString().Trim() != "")
            strCondition += " AND Name like '%" + txtCarrsSearch.Text.ToString().Trim() + "%'";
        #region Build List
        int nNumOfPages = 0;

        DataTable dtList;
        BuildList(strCondition, NumOfItemsPerPage, nPage, out nNumOfPages, out dtList, null, null);
        if (nPage > nNumOfPages) nPage = 1;

        rptData.DataSource = dtList;
        rptData.DataBind();
        #endregion
        #region Build Pager
        CommonFunctions.BuildPager(Request, nNumOfPages, nPage, strPageID, ContainerPage, out strPager);
        #endregion

    }
}
